#import "ChivoxCfg2.h"

#include "cJSON.h"


@implementation ChivoxCfg2
{
    BOOL _isArray;
    ChivoxCfg2 *_parent;
    cJSON *_json;
}

- (id)init {
    if (self = [super init]) {
        self->_isArray = false;
        self->_parent = NULL;
        self->_json = cJSON_CreateObject();
    }
    return self;
}

- (id)initSubArray:(ChivoxCfg2 *)parent :(NSString *)name {
    if (self = [super init]) {
        self->_isArray = true;
        self->_parent = parent;
        self->_json = cJSON_CreateArray();
        cJSON_AddItemToObject(parent->_json, [name UTF8String], self->_json);
    }
    return self;
}

- (id)initSubDict:(ChivoxCfg2 *)parent :(NSString *)name {
    if (self = [super init]) {
        self->_isArray = false;
        self->_parent = parent;
        self->_json = cJSON_CreateObject();
        cJSON_AddItemToObject(parent->_json, [name UTF8String], self->_json);
    }
    return self;
}

- (void)dealloc {
    if (self->_json) {
        cJSON_Delete(self->_json);
        self->_json = NULL;
    }
}

- (ChivoxCfg2 *)dict:(NSString *)name {
    return [[ChivoxCfg2 alloc] initSubDict:self :name];
}

- (ChivoxCfg2 *)array:(NSString *)name {
    return [[ChivoxCfg2 alloc] initSubArray:self :name];
}

- (ChivoxCfg2 *)end {
    if (self->_parent) {
        return self->_parent;
    }
    return self;
}

- (ChivoxCfg2 *)addBool:(BOOL)value {
    if (self->_isArray) {
        cJSON* item = cJSON_CreateBool(value);
        cJSON_AddItemToArray(self->_json, item);
    }
    return self;
}

- (ChivoxCfg2 *)addInt:(int)value {
    if (self->_isArray) {
        cJSON *item = cJSON_CreateNumber(value);
        cJSON_AddItemToArray(self->_json, item);
    }
    return self;
}

- (ChivoxCfg2 *)addDouble:(double)value {
    if (self->_isArray) {
        cJSON *item = cJSON_CreateNumber(value);
        cJSON_AddItemToArray(self->_json, item);
    }
    return self;
}

- (ChivoxCfg2 *)addString:(NSString *)value {
    if (self->_isArray) {
        cJSON *item = cJSON_CreateString([value UTF8String]);
        cJSON_AddItemToArray(self->_json, item);
    }
    return self;
}

- (ChivoxCfg2 *)setBool:(NSString *)name :(BOOL)value {
    if (!self->_isArray) {
        cJSON_AddBoolToObject(self->_json, [name UTF8String], value);
    }
    return self;
}

- (ChivoxCfg2 *)setInt:(NSString *)name :(int)value {
    if (!self->_isArray) {
        cJSON_AddNumberToObject(self->_json, [name UTF8String], value);
    }
    return self;
}

- (ChivoxCfg2 *)setDouble:(NSString *)name :(double)value {
    if (!self->_isArray) {
        cJSON_AddNumberToObject(self->_json, [name UTF8String], value);
    }
    return self;
}

- (ChivoxCfg2 *)setString:(NSString *)name :(NSString *)value {
    if (!self->_isArray) {
        cJSON_AddStringToObject(self->_json, [name UTF8String], [value UTF8String]);
    }
    return self;
        
}

- (NSString *)buildJson {
    return NULL;
}

@end
